package com.unis.common.util;

import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 加密工具
 * Created by Administrator on 2018/12/28/028.
 */
public class CryptoUtil {


    private static final Logger LOG = LoggerFactory.getLogger(CryptoUtil.class);

    private static final String HEX_SEQ = "0123456789ABCDEF";
    private static final Properties ENV = new Properties();

    static {
        InputStream in = CryptoUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
        try {
            ENV.load(in);
        } catch (IOException e) {
            LOG.error(e.getMessage());
        }
    }

    private CryptoUtil() {}

    private static final String getCombinedSalt(String salt) {
        return ENV.getProperty("shiro.applicationSalt") + ":" + salt;
    }

    private static final Integer getIterations() {
        String propIter = ENV.getProperty("shiro.hashIterations");
        return Integer.parseInt(propIter);
    }

    public static final String getRandomSalt() {
        return new SecureRandomNumberGenerator().nextBytes().toBase64();
    }

    public static final String encodePassphrase(String rawPassphrase, String salt) {
        Integer hashIterations = getIterations();
        return new Sha512Hash(rawPassphrase, getCombinedSalt(salt), hashIterations).toBase64();
    }

    public static final String encodePassphrase(String rawPassphrase) {
        return encodePassphrase(rawPassphrase, getRandomSalt());
    }

    public static String str2Hex(String str) {
        String res = "";
        if (str != null && !"".equals(str)) {
            char[] hexChars = HEX_SEQ.toCharArray();
            StringBuilder builder = new StringBuilder();
            byte[] bytes = str.getBytes();
            for (int i = 0; i < bytes.length; i++) {
                byte b = bytes[i];
                int b_h = (b & 0xF0) >> 4, b_l = (b & 0x0F);
                builder.append(hexChars[b_h]).append(hexChars[b_l]);
            }
            res = builder.toString();
        }
        return res;
    }

    public static String hex2Str(String hexStr) {
        String res = "";
        if (hexStr != null && !"".equals(hexStr)) {
            char[] hexChars = hexStr.toCharArray();
            byte[] orgin = new byte[hexChars.length / 2];
            for (int i = 0; i < orgin.length; i++) {
                int b = (HEX_SEQ.indexOf(hexChars[2 * i]) << 4 | HEX_SEQ.indexOf(hexChars[2 * i + 1]));
                orgin[i] = (byte) (b & 0xFF);
            }
            res = new String(orgin);
        }
        return res;
    }


}
